package com.wgy.day29多线程.解决线程安全问题的方式.静态同步方法;

/**
 * Created by pc on 2020/11/27 22:04
 * Description: LearningJava
 */

class RunnableImpl implements Runnable {

    private static int ticket = 100;

    @Override
    public void run() {
        System.out.println("this:" + this);
        //使用死循环,让卖票一直重复执行
        while (true) {
            playTicket02();
        }
    }

    public static void playTicket02() {

        synchronized (RunnableImpl.class) {
            //先判断票是否存在
            if (ticket > 0) {
                //提高安全问题出现的概率,让程序睡眠
                try {
                    Thread.sleep(10);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //票存在,卖票,ticket--
                System.out.println(Thread.currentThread().getName() + "-->正在买第" + ticket + "张票");
                ticket--;
            }
        }

    }
}


